<template>
  <div class="goods-container">
    <!-- 筛选条件 -->
    <div class="filter-content">
      <div class="filter-btn">
        <div class="filter-title">
          <i class="el-icon-search"></i>
          <span class="">筛选搜索</span>
        </div>
        <div>
          <el-button size="small" @click="resetFilter">重置</el-button>
          <el-button type="primary" size="small" @click="submitFilter">查询结果</el-button>
        </div>
      </div>
      <div class="filter-form">
        <!-- 商品名称 -->
        <div class="filter-item">
          <div>
            <span>商品名称：</span>
            <el-input placeholder="请输入商品名称" v-model="goodsName"> </el-input>
          </div>
        </div>
        <!-- 商品货号 -->
        <div class="filter-item">
          <div>
            <span>商品货号：</span>
            <el-input placeholder="请输入商品货号" v-model="goodsSpecs"> </el-input>
          </div>
        </div>
        <!-- 商品分类 -->
        <div class="filter-item">
          <div>
            <span>商品分类：</span>
            <el-cascader v-model="selectValue" :options="selectOptions" placeholder="请选择商品分类"></el-cascader>
          </div>
        </div>
        <!-- 是否是新品 -->
        <div class="filter-item">
          <div>
            <span>是否新品：</span>
            <el-select v-model="newValue" placeholder="请选择">
              <el-option
                v-for="item in [
                  { value: 0, label: '全部' },
                  { value: 1, label: '新品' },
                  { value: 2, label: '非新品' }
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @change="recommendChange"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="filter-item">
          <div>
            <span>是否推荐：</span>
            <el-select v-model="recommendValue" placeholder="请选择">
              <el-option
                v-for="item in [
                  { value: 0, label: '全部' },
                  { value: 1, label: '推荐' },
                  { value: 2, label: '非推荐' }
                ]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @change="newChange"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </div>
    </div>
    <!-- 数据列表 -->
    <div class="goods-title">
      <div>
        <i class="el-icon-tickets"></i>
        <span style="margin-left: 5px">数据列表</span>
      </div>
      <div>
        <el-button type="primary" size="small" @click="router.push('/home/add/goods')">添加</el-button>
      </div>
    </div>
    <!-- 数据表格 -->
    <div class="goods-list">
      <el-table :data="tableData.list" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="编号" width="80"> </el-table-column>
        <el-table-column prop="name" label="商品名称" width="200"></el-table-column>
        <el-table-column prop="img" label="商品图片" width="120">
          <template #default="scope">
            <ElImage :src="scope.row.img" alt="" />
          </template>
        </el-table-column>
        <el-table-column prop="no" label="商品货号" width="130"> </el-table-column>
        <el-table-column prop="desc" width="200" label="商品描述"> </el-table-column>
        <el-table-column prop="price" label="商品价格"> </el-table-column>
        <el-table-column prop="stock" label="商品库存"> </el-table-column>
        <el-table-column prop="specs" label="商品规格"> </el-table-column>
        <el-table-column prop="sell" label="商品销量"> </el-table-column>
        <el-table-column label="商品标签" prop="tag" width="130">
          <template #default="scope">
            <div>新品：<el-switch v-model="scope.row.tag.isNew" @change="newChange(scope.row.tag.isNew, scope.row.id)"></el-switch></div>
            <div style="margin-top: 5px">推荐：<el-switch v-model="scope.row.tag.isRecommend" @change="recommendChange(scope.row.tag.isRecommend, scope.row.id)"></el-switch></div>
            <div>轮播：<el-switch v-model="scope.row.tag.isBanner" @change="bannerChange(scope.row.tag.isBanner, scope.row.id)"></el-switch></div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <div style="margin-bottom: 5px"><el-button size="small" @click="getGoodsInfo(scope.row.id)">查看</el-button></div>
            <div style="margin-bottom: 5px"><el-button size="small" @click="handleEdit(scope.row.id)">编辑</el-button></div>
            <div><el-button size="small" type="danger" :loading="scope.row.loading" @click="handleDelete(scope.row)">删除</el-button></div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页导航 -->
      <div class="pagination-container">
        <div class="option-container">
          <div>
            <el-select v-model="value" placeholder="批量操作">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </div>
          <div class="btn">
            <el-button type="primary" @click="setRecommendOrNew" :loading="selectLoading">确定</el-button>
          </div>
        </div>
        <div class="pagination"><el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" background> </el-pagination></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from '@/utils/request'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

// 创建路由对象
const router = useRouter()

const options = reactive([
  {
    // 下拉菜单选项
    value: 'tRecommend',
    label: '设为推荐'
  },
  {
    value: 'fRecommend',
    label: '取消推荐'
  },
  {
    value: 'tNew',
    label: '设为最新'
  },
  {
    value: 'fNew',
    label: '取消最新'
  }
])
let selectOptions = reactive([])
let selectValue = reactive([])
let tableData = reactive({ list: [] })
let selectLoading = ref(false)
let value = ref('')
let goodsName = ref('')
let goodsSpecs = ref('')
let total = ref(0)
let pageSize = ref(5)
let currentPage = ref(1)
let newValue = ref(0)
let recommendValue = ref(0)
let multipleSelection = reactive([]) // 表格中选中的商品数据
let allGoodsList = reactive([]) // 保存所有的商品数据

// 重置筛选条件
const resetFilter = () => {
  selectValue = ref([])
  newValue.value = 0
  recommendValue.value = 0
  goodsName.value = ''
  goodsSpecs.value = ''
}
// 获取商品列表
const getGoodsList = async () => {
  try {
    const data = await axios.get('/bus/goods/list')
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      total.value = data.data.length
      allGoodsList = data.data

      for (let i = (currentPage.value - 1) * 5; i < currentPage.value * pageSize.value; i++) {
        if (allGoodsList[i]) {
          tableData.list.push({
            id: allGoodsList[i].id,
            name: allGoodsList[i].goods_name,
            img: 'http://127.0.0.1:5500' + allGoodsList[i].goods_img,
            no: allGoodsList[i].article_no,
            desc: allGoodsList[i].goods_desc,
            price: allGoodsList[i].goods_price,
            stock: allGoodsList[i].goods_stock,
            specs: allGoodsList[i].specs,
            sell: allGoodsList[i].goods_sell_num,
            tag: reactive({
              isNew: allGoodsList[i].is_new == 1 ? true : false,
              isRecommend: allGoodsList[i].is_recommend == 1 ? true : false,
              isBanner: allGoodsList[i].is_banner == 1 ? true : false
            }),
            loading: false
          })
        } else {
          break
        }
      }
    } else if (data.code === 403 || data.msg === '身份认证错误') {
      ElMessage({
        type: 'error',
        message: data.msg
      })
      localStorage.removeItem('bus_token')
      router.replace('/login')
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch (err) {
    ElMessage.error(err)
  }
}

// 设置最新或者推荐
const setRecommendOrNew = async () => {
  // 必须选择一项
  if (value.value === '') return ElMessage({ type: 'error', message: '请选择操作选项！' })
  // 必须有商品选中
  if (multipleSelection.length === 0) return ElMessage({ type: 'error', message: '至少选择一件商品！' })
  // 创建商品id
  let ids = ''
  multipleSelection.forEach((item) => {
    ids += item.id + ','
  })
  ids = ids.slice(0, -1)
  // 创建请求参数
  let params = { ids }
  switch (value.value) {
    case 'tNew':
      params = { ids, is_new: true }
      break
    case 'fNew':
      params = { ids, is_new: false }
      break
    case 'fRecommend':
      params = { ids, is_recommend: false }
      break
    case 'tRecommend':
      params = { ids, is_recommend: true }
      break
    default:
      ElMessage({ type: 'error', message: '选项错误！' })
  }
  selectLoading.value = true
  try {
    const data = await axios.post('/bus/update/goods/neworrecommend', params)
    tableData.list = []
    if (data.code === 0) {
      // 更新数据成功
      ElMessage({ type: 'success', message: data.msg })
      // currentPage.value = 1
      getGoodsList()
      // 重新获取商品数据
    } else {
      ElMessage({ type: 'error', message: data.msg })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    selectLoading.value = false
  }
}

// 表格选中处理函数
const handleSelectionChange = (val) => {
  multipleSelection = val
}
// 切换页数
const handleCurrentChange = (val) => {
  currentPage.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  for (let i = (currentPage.value - 1) * pageSize.value; i < currentPage.value * pageSize.value; i++) {
    if (allGoodsList[i]) {
      tableData.list.push({
        loading: false,
        id: allGoodsList[i].id,
        name: allGoodsList[i].goods_name,
        img: 'http://127.0.0.1:5500' + allGoodsList[i].goods_img,
        no: allGoodsList[i].article_no,
        desc: allGoodsList[i].goods_desc,
        price: allGoodsList[i].goods_price,
        stock: allGoodsList[i].goods_stock,
        specs: allGoodsList[i].specs,
        sell: allGoodsList[i].goods_sell_num,
        tag: { isNew: allGoodsList[i].is_new === '1' ? true : false, isRecommend: allGoodsList[i].is_recommend === '1' ? true : false }
      })
    }
  }
}
// 切换每一页显示的长度
const handleSizeChange = (val) => {
  pageSize.value = val
  tableData.list = []
  // 根据当前页和每一页长度进行数据渲染
  for (let i = (currentPage.value - 1) * pageSize.value; i < currentPage.value * pageSize.value; i++) {
    if (allGoodsList[i]) {
      tableData.list.push({
        loading: false,
        id: allGoodsList[i].id,
        name: allGoodsList[i].goods_name,
        img: 'http://127.0.0.1:5500' + allGoodsList[i].goods_img,
        no: allGoodsList[i].article_no,
        desc: allGoodsList[i].goods_desc,
        price: allGoodsList[i].goods_price,
        stock: allGoodsList[i].goods_stock,
        specs: allGoodsList[i].specs,
        sell: allGoodsList[i].goods_sell_num,
        tag: { isNew: allGoodsList[i].is_new === '1' ? true : false, isRecommend: allGoodsList[i].is_recommend === '1' ? true : false }
      })
    }
  }
}

// 切换是否是轮播图展示
const bannerChange = async (val, id) => {
  try {
    const data = await axios.post('/bus/update/goods/banner/' + id, {
      banner: val
    })
    if (data.code === 0) {
      ElMessage({
        type: 'success',
        message: data.msg
      })
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 切换商品是否为新品
const newChange = async (val, id) => {
  try {
    const data = await axios.post('/bus/update/goods/new/' + id, {
      is_new: val
    })
    if (data.code === 0) {
      ElMessage({
        type: 'success',
        message: data.msg
      })
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 切换商品的推荐状态
const recommendChange = async (val, id) => {
  try {
    const data = await axios.post('/bus/update/goods/recommend/' + id, {
      recommend: val
    })
    if (data.code === 0) {
      ElMessage({
        type: 'success',
        message: data.msg
      })
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 删除商品
const handleDelete = async (row) => {
  row.loading = true
  try {
    const data = await axios.post('/bus/del/goods/' + row.id)
    if (data.code === 0) {
      // 删除成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 重新获取商品列表
      getGoodsList()
    } else {
      // 删除失败
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  } finally {
    row.loading = false
  }
}

// 提交筛选条件筛选商品数据
const submitFilter = async () => {
  // 创建请求参数
  // 验证商品货号是否正确
  if (goodsSpecs.value !== '' && !/^[A-Za-z]{1,}\d+/.test(goodsSpecs.value)) {
    return ElMessage({
      type: 'error',
      message: '商品货号为数字字母组合，且字母在前，数字在后！'
    })
  }
  try {
    const data = await axios.get('/bus/filter/goods/list', {
      params: {
        name: goodsName.value,
        specs: goodsSpecs.value,
        cate_id: selectValue[1] ? selectValue[1] : selectValue[0] ? selectValue[0] : '',
        is_new: newValue.value,
        is_recommend: recommendValue.value
      }
    })
    if (data.code === 0) {
      // 获取成功
      ElMessage({
        type: 'success',
        message: data.msg
      })
      // 对数据进行处理
      total.value = data.data.length
      currentPage.value = 1
      allGoodsList = data.data
      tableData.list = []
      for (let i = (currentPage.value - 1) * 5; i < currentPage.value * pageSize.value; i++) {
        if (allGoodsList[i]) {
          tableData.list.push({
            id: allGoodsList[i].id,
            name: allGoodsList[i].goods_name,
            img: 'http://127.0.0.1:5500' + allGoodsList[i].goods_img,
            no: allGoodsList[i].article_no,
            desc: allGoodsList[i].goods_desc,
            price: allGoodsList[i].goods_price,
            stock: allGoodsList[i].goods_stock,
            specs: allGoodsList[i].specs,
            sell: allGoodsList[i].goods_sell_num,
            tag: { isNew: allGoodsList[i].is_new === '1' ? true : false, isRecommend: allGoodsList[i].is_recommend === '1' ? true : false },
            loading: false
          })
        } else {
          break
        }
      }
    } else {
      ElMessage({
        type: 'error',
        message: data.msg
      })
    }
  } catch {
    ElMessage.error('请求失败！')
  }
}

// 编辑商品
const handleEdit = (id) => {
  router.push('/home/edit/goods/' + id)
}
// 查看商品
const getGoodsInfo = (id) => {
  router.push('/home/goods/info/' + id)
}
// 获取一级分类
const getCateList = async () => {
  const data = await axios.get('/bus/category/list')
  if (data.code === 0) {
    // 获取一级分类成功
    data.data.forEach((item) => {
      // 遍历一级分类发起请求获取二级分类
      getSonCateList(item)
    })
  } else {
    ElMessage({
      type: 'error',
      message: data.msg
    })
  }
}
// 获取二级分类
const getSonCateList = async (item) => {
  const cate = {
    value: item.id,
    label: item.name
  }
  const data = await axios.get('/bus/category/list/' + item.id)
  if (data.code === 0) {
    // 获取成功
    if (data.data.length > 0) {
      cate.children = []
      data.data.forEach((cateItem) => {
        cate.children.push({
          value: cateItem.id,
          label: cateItem.name
        })
      })
    }
    selectOptions.push(cate)
  } else {
    ElMessage({
      type: 'error',
      message: data.msg
    })
  }
}

getGoodsList()
getCateList()
</script>

<style lang="scss" scoped>
.goods-container {
  padding: 50px;

  .filter-content {
    padding: 15px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;

    .filter-btn {
      display: flex;
      justify-content: space-between;

      .filter-title {
        span {
          margin-left: 5px;
        }
      }
    }
    .filter-form {
      margin-top: 15px;
      padding: 0 30px;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }

    .filter-item {
      width: 26%;
      margin-bottom: 10px;

      div {
        display: flex;
        align-items: center;

        span {
          white-space: nowrap;
        }
      }
    }
  }
  .goods-title {
    padding: 15px;
    margin-top: 30px;
    min-width: 1120px;
    border: 1px solid #e1e1e1;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .goods-list {
    margin-top: 30px;
    min-width: 1120px;
    background-color: #fff;
    :deep(.el-table .el-table__cell) {
      text-align: center;
    }

    .pagination-container {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;

      .option-container {
        display: flex;
        align-items: center;

        .btn {
          margin-left: 15px;
        }
      }
    }
  }
}
</style>
